package com.liqi.generate;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableField;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.liqi.frame.comm.util.IdUtil;
import org.apache.commons.lang.StringUtils;

import java.util.*;

/**
 * 代码生成器
 * @author liqi on 2019/10/12 0012. liqiwork@qq.com
 */
public class MyGenerator {
    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("liqi");
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        // 是否覆盖已有文件
        gc.setFileOverride(false);
        gc.setMapperName("%sDao");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/food?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root123");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
//        pc.setModuleName(scanner("模块名"));

        String moduleName = scanner("模块名");
        pc.setParent("com.liqi.biz");
        pc.setController("controller."+moduleName);
        pc.setService("service."+moduleName);
        pc.setServiceImpl("service."+moduleName+".impl");
        pc.setEntity("po."+moduleName);
        pc.setMapper("dao."+moduleName);
//        pc.setModuleName(moduleName);
//        pc.setPathInfo()
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                String jsPath = "<@baseUrl url='/static/js/"+moduleName;
                map.put("jsPath", jsPath);
                map.put("moduleName", moduleName);
                String hasPermissionTag = "<@hasPermission key=";
                map.put("hasPermissionTag", hasPermissionTag);

                List<TableInfo> tableInfoList = mpg.getConfig().getTableInfoList();
                if (tableInfoList!=null && tableInfoList.size()>0) {
                    TableInfo tableInfo = tableInfoList.get(0);
                    List<TableField> tableFieldList = new ArrayList<>();
                    tableFieldList.addAll(tableInfo.getCommonFields());
                    tableFieldList.addAll(tableInfo.getFields());
                    if (tableFieldList!=null && tableFieldList.size()>0) {
                        map.put("tableFieldList", tableFieldList);
                    }
                }
                this.setMap(map);
            }
        };

        // 如果模板引擎是 freemarker
//        String templatePath = "/templates/mapper.xml.ftl";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig("/templates/generator/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/src/main/java/com/liqi/biz/dao/" + moduleName
                        + "/" + tableInfo.getEntityName() + "Dao" + StringPool.DOT_XML;
            }
        });

        focList.add(new FileOutConfig("/templates/generator/controllerAjax.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/src/main/java/com/liqi/biz/controller/" + moduleName
                        + "/" + tableInfo.getEntityName() + "AjaxController" + StringPool.DOT_JAVA;
            }
        });

        focList.add(new FileOutConfig("/templates/generator/view.html.ftl") {
            //生成html
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/resources/templates/" + moduleName
                        + "/" + StrUtil.lowerFirst(tableInfo.getEntityName()) + ".html";
            }
        });

        focList.add(new FileOutConfig("/templates/generator/view.js.ftl") {
            //生成js
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/resources/static/static/js/" + moduleName
                        + "/" + StrUtil.lowerFirst(tableInfo.getEntityName()) + ".js";
            }
        });

        focList.add(new FileOutConfig("/templates/generator/viewForm.html.ftl") {
            //生成form html
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/resources/templates/" + moduleName
                        + "/" + StrUtil.lowerFirst(tableInfo.getEntityName()) + "Form.html";
            }
        });

        focList.add(new FileOutConfig("/templates/generator/viewForm.js.ftl") {
            //生成form js
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/resources/static/static/js/" + moduleName
                        + "/" + StrUtil.lowerFirst(tableInfo.getEntityName()) + "Form.js";
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录");
                return false;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        templateConfig.setController("templates/generator/controller.java");
        templateConfig.setService("templates/generator/service.java");
        templateConfig.setServiceImpl("templates/generator/serviceImpl.java");
        templateConfig.setMapper("templates/generator/mapper.java");
        templateConfig.setEntity("templates/generator/entity.java");
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 表与执久类 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("com.liqi.frame.comm.base.BaseEntity");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(false);
        // 公共父类
//        strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        String tableName = scanner("表名，多个英文逗号分割");
        strategy.setInclude(tableName.split(","));
//        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(false);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();


        String insertMenu_id = IdUtil.getId()+"";
        String insertMenu_permission_key = moduleName+"_"+tableName;
        String insertMenu_permission_name = tableName;
        String insertMenu_permission_type = "menu";
        String insertMenu_parent_id = "89a7fc35bf574564a0c54a23a7d50560";
        Integer insertMenu_level = 2;
        String insertMenu_comment = "自动生成的菜单";
        Float insertMenu_order_id = (float)1.0;
        String insertMenu_target = "_self";
        String insertMenu_href = tableName+"/"+tableName;
        String insertMenuSql = "INSERT ignore INTO sys_permission (id, permission_key, permission_name, permission_type, parent_id, level, comment, order_id, target, href) VALUES (" +
                "'"+insertMenu_id+
                "', '"+insertMenu_permission_key+
                "', '"+insertMenu_permission_name+
                "', '"+insertMenu_permission_type+
                "', '"+insertMenu_parent_id+
                "', "+insertMenu_level+
                ", '"+insertMenu_comment+
                "', "+insertMenu_order_id+
                ", '"+insertMenu_target+
                "', '"+insertMenu_href+"');";

        String insertRolePermission_id = IdUtil.getId()+"";
        String insertRolePermission_role_id = "1";
        String insertRolePermission_permission_id = insertMenu_id;
        String insertRolePermissionSql = "INSERT ignore INTO sys_role_permission (id, role_id, permission_id) VALUES (" +
                "'"+insertRolePermission_id+
                "', '"+insertRolePermission_role_id+
                "', '"+insertRolePermission_permission_id+"');";

        System.out.println("\n");
        System.out.println("==========================================菜单SQL=============================================\n");
        System.out.println(insertMenuSql+"\n\n"+insertRolePermissionSql);
        System.out.println("");
        System.out.println("==========================================菜单SQL=============================================\n");

//        Map<String, Object> map = new HashMap<String, Object>();
//        this.setMap(map);
//        List<TableInfo> l = mpg.getConfig().getTableInfoList();
    }
}
